<template>
  <div class="wechatAuthEditBox">
    <div class="wechatAuthEdit">
      <div class="wechat_left">
        <p class="wechat_bg_top">
          {{data.nick_name}}
        </p>
        <div class="wechat_bg_bottom">
          <div class="main_menu" v-for="(menu, index) in mainMenus" :class="{active: currentLevel === menu.level}" >
            <span class="main_menu_name" @click="MainMenuClick(menu)">{{menu.name}}</span>
            <p class="wechat_sub_container" v-if="currentLevel.substring(0, 1) === menu.level">
            <span v-for="(sub, index2) in menu.sub_button"
                  class="wechat_sub_menu"
                  :class="{active: currentLevel === sub.level}"
                  @click="SubMenuClick(sub)"
            >
              {{sub.name}}
            </span>
              <span class="wechat_sub_menu" v-show="menu.sub_button.length < 5" @click="addSubMenu(menu, index)" style="border-bottom: 0;">
              <i class="el-icon-plus"></i>
            </span>
              <b class="el-icon-arrow-down wechat_sanjiao"></b>
            </p>
          </div>
          <div class="main_menu" v-show="mainMenus.length < 3" @click="addMainMenu">
          <span class="main_menu_name">
            <i class="el-icon-plus"></i>
          </span>
          </div>
        </div>
      </div>
      <div class="wechat_right">
        <wechat-menu-edit v-if="currentMenu.level && !deleteAll"
                          :menudata="currentMenu"
                          :weixindata="data"
                          @save="save"
                          @delete="deleteMenu"
                          :deleteAll="deleteAll"
                          :wechatCsr="wechatCsr"></wechat-menu-edit>
        <div v-if="deleteAll" class="deleteAll">
          <p class="font16">{{$t('configLazyLoad.channel.wexinTip27')}}</p>
          <el-button type="primary" class="primary_btn" @click="save">{{$t('configLazyLoad.channel.wexinTip28')}}</el-button>
        </div>
      </div>
    </div>
    <div class="footer" v-if="type === 'add'">
      <el-button class="primary_btn" @click.stop="backPreviousStep()" type="primary" v-if="type === 'add'">{{$t('public.confirm')}}</el-button>
    </div>
  </div>
</template>

<script>
  import wechatMenuEdit from './wechatMenuEdit.vue'
  import { deepClone, isEmptyObj } from '@/utils/m7Utils'
  import {checkform} from '@/utils/validate'
  import * as uuid from 'uuid'
  export default {
    name: 'wechatAuthEdit',
    data () {
      return {
        data: '',
        mainMenus: [
        ],
        currentLevel: '',
        currentMenu: {},
        wechatCsr: 0,
        deleteAll: false,
        error: false,
        errorLevel: ''
      }
    },
    props: ['weixindata', 'type'],
//    watch: {
//      mainMenus: {
//        deep: true,
//        handler () {
//          let status = 0
//          let data = this.mainMenus
//          data.length && data.forEach((main) => {
//            if (main.sub_button.length === 0) {
//              if (main.type === '3') {
//                status++
//              }
//            } else {
//              main.sub_button.forEach((sub) => {
//                if (sub.type === '3') {
//                  status++
//                }
//              })
//            }
//          })
//          this.wechatCsr = status
//        }
//      }
//    },
    methods: {
      deleteMenu () {
        if (this.currentLevel.length === 1) {
          this.$confirm(this.$t('configLazyLoad.channel.wexinTip29') + this.currentMenu.name + this.$t('configLazyLoad.channel.wexinTip30'), this.$t('public.tip'), {
            confirmButtonText: this.$t('public.confirm'),
            cancelButtonText: this.$t('public.cancel'),
            cancelButtonClass: 'primary_btn',
            confirmButtonClass: 'primary_btn',
            type: 'warning'
          }).then(() => {
            let index = this.mainMenus.findIndex((elem) => {
              return elem.level === this.currentLevel
            })
            this.mainMenus.splice(index, 1)
            if (this.mainMenus.length > 0) {
              this.currentLevel = this.mainMenus[0].level
              this.currentMenu = this.mainMenus[0]
            } else {
              this.deleteAll = true
              this.currentLevel = ''
              this.currentMenu = {}
            }
          }).catch(() => {
          })
        } else {
          let level = this.currentLevel.split('_')
          let index1 = this.mainMenus.findIndex((elem) => {
            return elem.level === level[0]
          })
          let index2 = this.mainMenus[index1].sub_button.findIndex((sub) => {
            return sub.level === this.currentLevel
          })
          this.mainMenus[index1].sub_button.splice(index2, 1)
          if (this.mainMenus[index1].sub_button.length > 0) {
            this.currentLevel = this.mainMenus[index1].sub_button[this.mainMenus[index1].sub_button.length - 1].level
            this.currentMenu = this.mainMenus[index1].sub_button[this.mainMenus[index1].sub_button.length - 1]
          } else {
            this.currentLevel = this.mainMenus[index1].level
            this.currentMenu = this.mainMenus[index1]
          }
        }
      },
      save () {
        console.log(this.mainMenus)
        let data = deepClone(this.mainMenus)
        let menus = {
          button: []
        }
        let events = []
        this.error = false
        data.length && data.forEach((item) => {
          if (item.sub_button.length === 0) {
            let o = this.formatData(item)
            if (!o) { return false }
            menus.button.push(o[0])
            if (!isEmptyObj(o[1])) {
              events.push(o[1])
            }
          } else if (item.sub_button.length > 0) {
            let dataObj = {
              name: item.name,
              sub_button: []
            }
            item.sub_button.forEach((sub) => {
              let o = this.formatData(sub)
              if (!o) { return false }
              dataObj.sub_button.push(o[0])
              if (!isEmptyObj(o[1])) {
                events.push(o[1])
              }
            })
            menus.button.push(dataObj)
          }
        })
        if (this.error) {
          this.currentLevel = this.errorLevel
          this.errorLevel = ''
          if (this.currentLevel.length === 1) {
            let index = this.mainMenus.findIndex((menu) => {
              return menu.level === this.currentLevel
            })
            this.currentMenu = this.mainMenus[index]
          } else {
            let index1 = this.mainMenus.findIndex((menu) => {
              return menu.level === this.currentLevel.split('_')[0]
            })
            let index2 = this.mainMenus[index1].sub_button.findIndex((sub) => {
              return sub.level === this.currentLevel
            })
            this.currentMenu = this.mainMenus[index1].sub_button[index2]
          }
          return
        }
        let robot = 0
        for (let i = 0; i < events.length; i++) {
          if (events[i].eventKey === 'robot') {
            robot++
            if (robot > 1) {
              this.$message.error(this.$t('configLazyLoad.channel.wexinTip31'))
              return
            }
          }
        }
        let senddata = {
          _id: this.weixindata._id,
          menus: menus,
          events: events
        }
        this.$store.dispatch('createWeixinMenu', senddata).then((res) => {
          if (res.success) {
            this.$message.success(this.$t('configLazyLoad.channel.wexinTip32'))
          }
        })
      },
      formatData (menu) {
        let weixinid = this.weixindata._id
        let obj = {}
        let event = {}
        if (menu.type === '0' && menu.imgOrTxtType === 'Txt') {
          // type等于0主菜单内容为：发送消息
          let key = uuid.v1()
          if (menu.txtContent === '' && !this.error) {
            this.$message.error('[' + menu.name + this.$t('configLazyLoad.channel.wexinTip33'))
            this.error = true
            this.errorLevel = menu.level
          } else if (menu.txtContent.length > 600 && !this.error) {
            this.error = true
            this.errorLevel = menu.level
            this.$message.error('[' + menu.name + this.$t('configLazyLoad.channel.wexinTip34'))
          } else {
            obj = {
              type: 'click',
              name: menu.name,
              key: key
            }
            event = {
              appid: weixinid,
              eventKey: key,
              content: menu.txtContent,
              contentType: 'text'
            }
          }
        } else if (menu.type === '0' && menu.imgOrTxtType === 'imgTxt') {
          if (menu.article_id) {
            obj = {
              type: 'article_id',
              name: menu.name,
              article_id: menu.article_id
            }
          } else {
            if (!menu.media_id) {
              this.$message.error(this.$t('configLazyLoad.channel.wexinTip35'))
              this.error = true
              this.errorLevel = menu.level
            }
            obj = {
              type: 'media_id',
              name: menu.name,
              media_id: menu.media_id
            }
          }
        } else if (menu.type === '1') {
          if ((menu.urlContent === 'http://' || menu.urlContent === '') && !this.error) {
            this.$message.error(this.$t('configLazyLoad.channel.wexinTip36'))
            this.error = true
            this.errorLevel = menu.level
          } else if (checkform(menu.urlContent, 'Url') && !this.error) {
            this.error = true
            this.errorLevel = menu.level
            this.$message.error(this.$t('configLazyLoad.channel.wexinTip37'))
          } else {
            obj = {
              type: 'view',
              name: menu.name,
              url: menu.urlContent
            }
          }
        } else if (menu.type === '2') {
          if (menu.robotContent === '' && !this.error) {
            this.$message.error('[' + menu.name + this.$t('configLazyLoad.channel.wexinTip38'))
            this.error = true
            this.errorLevel = menu.level
          } else if (menu.robotContent.length > 600 && !this.error) {
            this.error = true
            this.errorLevel = menu.level
            this.$message.error('[' + menu.name + this.$t('configLazyLoad.channel.wexinTip39'))
          } else {
            obj = {
              type: 'click',
              name: menu.name,
              key: 'robot'
            }
            event = {
              appid: weixinid,
              eventKey: 'robot',
              content: menu.robotContent,
              contentType: 'text'
            }
          }
        } else if (menu.type === '3') {
          obj = {
            type: 'view',
            name: menu.name,
            url: menu.evaluateContent
          }
        } else if (menu.type === '4') { // 小程序
          obj = {
            type: 'miniprogram',
            name: menu.name,
            appid: menu.appid,
            pagepath: menu.pagepath,
            url: menu.url
          }
        }
        return [obj, event]
      },
      reFormatData (data) {
        data && data.length && data.forEach((item, index1) => {
          if (!item.sub_button) {
            let o = this.reFormatMenu(item, index1)
            o['sub_button'] = []
            this.mainMenus.push(o)
          } else {
            let m = {
              name: item.name,
              sub_button: [],
              level: index1 + 1 + ''
            }
            let subArray = []
            if (Array.isArray(item.sub_button)) {
              subArray = item.sub_button
            } else if (item.sub_button && item.sub_button.list) {
              subArray = item.sub_button.list
            }
            subArray.forEach((sub, index2) => {
              let n = this.reFormatMenu(sub, index1, index2)
              m.sub_button.push(n)
            })
            this.mainMenus.push(m)
          }
        })
      },
      reFormatMenu (menu, index1, index2) {
        let obj = {
          name: menu.name
        }
        if (index1 !== undefined && index2 === undefined) {
          obj.level = index1 + 1 + ''
        } else if (index1 !== undefined && index2 !== undefined) {
          obj.level = (index1 + 1) + '_' + (index2 + 1)
        }
        if (menu.type === 'media_id') {
          obj.media_id = menu.media_id
          obj.type = '0'
          obj.imgOrTxtType = 'imgTxt'
        } else if (menu.type === 'article_id') {
          obj.article_id = menu.article_id
          obj.type = '0'
          obj.imgOrTxtType = 'imgTxt'
        } else if (menu.type === 'click' && !menu.robot) {
          obj.txtContent = menu.key
          obj.type = '0'
          obj.imgOrTxtType = 'Txt'
        } else if (menu.type === 'view' && menu.url.indexOf('state=evaluate_in') === -1) {
          obj.urlContent = menu.url
          obj.type = '1'
        } else if (menu.type === 'click' && menu.robot) {
          obj.robotContent = menu.key
          obj.type = '2'
        } else if (menu.type === 'view' && menu.url.indexOf('state=evaluate_in') > 0) {
          obj.evaluateContent = menu.url
          obj.type = '3'
        } else if (menu.type === 'miniprogram') {
          obj.type = '4'
          obj.appid = menu.appid
          obj.pagepath = menu.pagepath
          obj.url = menu.url
        }
        return obj
      },
      SubMenuClick (sub) {
        this.currentLevel = sub.level
        this.currentMenu = sub
      },
      MainMenuClick (menu) {
        this.currentLevel = menu.level
        this.currentMenu = menu
      },
      addSubMenu (menu, index) {
        let level = menu.sub_button.length + 1 + ''
        let newmenu = {
          name: this.$t('configLazyLoad.channel.wexinTip40'),
          level: index + 1 + '_' + level
        }
        menu.sub_button.push(newmenu)
        this.currentLevel = index + 1 + '_' + level
        this.currentMenu = newmenu
      },
      addMainMenu () {
        let level = this.mainMenus.length < 1 ? 0 : parseInt(this.mainMenus[this.mainMenus.length - 1].level)
        let newmenu = {
          name: this.$t('configLazyLoad.channel.wexinTip41'),
          sub_button: [],
          level: level + 1 + ''
        }
        this.mainMenus.push(newmenu)
        if (this.deleteAll) {
          this.deleteAll = false
        }
        this.currentLevel = level + 1 + ''
        this.currentMenu = newmenu
      },
      backPreviousStep () {
        this.$emit('preStep')
      }
    },
    mounted () {
      this.data = deepClone(this.weixindata)
      let data = {
        _id: this.weixindata._id
      }
      this.$store.dispatch('getWeixinMenu', data).then((res) => {
        res.menus && res.menus.button && this.reFormatData(res.menus.button)
        if (!this.mainMenus[0]) {
          return
        }
        this.currentLevel = this.mainMenus[0].level
        this.currentMenu = this.mainMenus[0]
      })
    },
    components: {
      wechatMenuEdit
    }
  }
</script>

<style lang="stylus" scoped>
  @import "./../../../../../assets/common.styl"
  .wechatAuthEdit
    margin 0 auto
    width 704px
    padding 10px
    border 10px solid #f5f5f5
    &:after
      display block
      content "clear"
      height 0
      clear both
      overflow hidden
      visibility hidden
    .wechat_left
      width 320px
      height 580px
      float left
      border 1px solid #e6e6e6
      margin-bottom 10px
      position relative
      .wechat_bg_top
        background url('./../../../../../assets/img/weixin_mobile_bg.png') no-repeat
        text-align center
        height 22px
        padding 32px 0 8px 0
        vertical-align bottom
        color #fff
      .wechat_bg_bottom
        background url('./../../../../../assets/img/weixin_mobile_bg.png') no-repeat
        width: 276px;
        position: absolute;
        bottom: 0;
        background-position: 0 -65px;
        white-space: nowrap;
        padding-left: 45px;
        display: -webkit-box;
        border-top: 1px solid #e6e6e6;
        height: 48px;
        .main_menu
          height: 48px;
          line-height: 48px;
          box-flex: 1.0;
          -webkit-box-flex: 1.0;
          border: 1px solid #e6e6e6;
          text-align: center;
          cursor: pointer;
          position: relative;
          margin: -1px 0 0 -1px;
          .main_menu_name
              display: block;
              min-width: 50px;
              min-height: 48px;
              background-color: #fafafa;
              cursor: pointer;
          .wechat_sub_container
            position: absolute;
            border: 1px solid #d0d0d0;
            width: 100%;
            max-height: 229px;
            left: -1px;
            bottom: 60px;
            background: #fafafa;
          .wechat_sub_menu
            display: block;
            position: relative;
            height: 45px;
            margin: 0 6px;
            padding: 0 5px;
            line-height: 45px;
            text-align: center;
            border-bottom: 1px solid #d0d0d0;
            overflow: hidden;
            text-overflow: ellipsis;
          .active
            margin: -1px -1px 0 -1px;
            padding: 0 1px;
            border: 1px solid $c-main;
          .wechat_sanjiao
            display: block;
            width: 8px;
            height: 8px;
            position: absolute;
            bottom: -8px;
            left: 50%;
            margin-left: -4px;
            -webkit-filter: grayscale(100%);
        .active
          border: 1px solid $c-main;
          color $c-main
          z-index: 2;
    .wechat_right
      float left
      width 338px
      padding 10px 14px
      background-color #f7f7f7
      height 560px
      margin-left 12px
      border 1px solid #e6e6e6
      position relative
      .deleteAll
        padding: 20px
        text-align center
        p
          margin-bottom 20px
  .footer
    margin-top 10px
    text-align center
  .weixinAuthStep
    .wechatAuthEditBox
      text-align left
</style>
